package com.ycy.smartcourseselection.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ycy.smartcourseselection.common.ResCodeEnum;
import com.ycy.smartcourseselection.common.ResData;
import com.ycy.smartcourseselection.dto.login.LoginDTO;
import com.ycy.smartcourseselection.entity.OpenIdManage;
import com.ycy.smartcourseselection.entity.Student;
import com.ycy.smartcourseselection.entity.Teacher;
import com.ycy.smartcourseselection.exception.CustomException;
import com.ycy.smartcourseselection.mapper.IOpenIdManageMapper;
import com.ycy.smartcourseselection.vo.login.ScanQrCodeRes;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class OpenIdManageService extends ServiceImpl<IOpenIdManageMapper, OpenIdManage> {
    @Resource
    private TeacherService teacherService;
    @Resource
    private StudentService studentService;
    @Resource
    private LoginService loginService;

    //微信绑定用户id(增加)
    public ResData<Boolean> addWxBind(OpenIdManage openIdManage) {
        String userId = openIdManage.getUserId();
        if(StrUtil.isBlank(userId)) throw new CustomException(ResCodeEnum.BAD_REQUEST,"userId不能为空");
        if(StrUtil.isBlank(openIdManage.getOpenId())) throw new CustomException(ResCodeEnum.BAD_REQUEST,"openId不能为空");

        validateTchAndStu(userId);

        return ResData.success(save(openIdManage));
    }

    //更换微信绑定(更新)
    public ResData<Boolean> updateWxBind(OpenIdManage openIdManage) {
        String userId = openIdManage.getUserId();
        String openId = openIdManage.getOpenId();
        if(StrUtil.isBlank(userId)) throw new CustomException(ResCodeEnum.BAD_REQUEST,"userId不能为空");
        if(StrUtil.isBlank(openId)) throw new CustomException(ResCodeEnum.BAD_REQUEST,"openId不能为空");
        validateTchAndStu(userId);

        QueryWrapper<OpenIdManage> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        List<OpenIdManage> list = list(wrapper);
        if(list.size() == 0) throw new CustomException(ResCodeEnum.BAD_REQUEST,"该userId的绑定记录不存在");
        if(list.size() > 1) throw new CustomException(ResCodeEnum.BAD_REQUEST,"错误地存在多个该userId的绑定记录");
        list.get(0).setOpenId(openId);

        return ResData.success(update(list.get(0),wrapper));
    }

    //轮询绑定微信
    public ResData<ScanQrCodeRes> bindWeiXinByQrCode(String userId, String timeStamp) {
        if(StrUtil.isBlank(userId)) throw new CustomException(ResCodeEnum.SERVER_ERROR,"用户id不能为空");
        if(StrUtil.isBlank(timeStamp)) throw new CustomException(ResCodeEnum.SERVER_ERROR,"时间戳不能为空");

        //验证是否已扫码
        ScanQrCodeRes currentScanRes = loginService.judgeIsScan(userId+timeStamp);
        if(currentScanRes == null) return ResData.success(null,"暂未扫码");
        loginService.clearCurrentScanRes(userId+timeStamp);  //当扫码之后，就清空状态数组中的数据

        //验证该微信是否已绑定其他账号
        String openId = currentScanRes.getOpenId();
        QueryWrapper<OpenIdManage> openIdWrapper = new QueryWrapper<>();
        openIdWrapper.eq("open_id",openId);
        List<OpenIdManage> openIdList = list(openIdWrapper);
        if(openIdList.size() > 1) throw new CustomException(ResCodeEnum.BAD_REQUEST, "错误地存在多个该userId的微信账号绑定信息");
        // System.out.println("userId  " + userId);
        // System.out.println("openIdList.get(0).getUserId()  " + openIdList.get(0).getUserId());
        if(openIdList.size() == 1 && !userId.equals(openIdList.get(0).getUserId())) {
            return ResData.success(null, "该微信已绑定其他账号："+ openIdList.get(0).getUserId());
        }

        //验证该userId是否已绑定微信。若未绑定，则绑定;若已绑定,则返回扫描信息用于前端可更换绑定
        QueryWrapper<OpenIdManage> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        List<OpenIdManage> openIdManageList = list(wrapper);
        if(openIdManageList.size() == 1) {
            if(openId.equals(openIdManageList.get(0).getOpenId())) return ResData.success(currentScanRes,"该账号已绑定微信");
            else return ResData.success(currentScanRes, "该账号已绑定其他微信");
        }
        if(openIdManageList.size() > 1) throw new CustomException(ResCodeEnum.BAD_REQUEST, "错误地存在多个该userId的微信账号绑定信息");

        //当openIdManageList.size() == 0,即没有查询到绑定记录的情况
        OpenIdManage openIdManage = new OpenIdManage();
        openIdManage.setOpenId(openId);
        openIdManage.setUserId(userId);
        Boolean isBind = addWxBind(openIdManage).getData();
        if (isBind) return ResData.success(currentScanRes, "绑定成功");
        else throw new CustomException(ResCodeEnum.SERVER_ERROR, "保存微信与账号绑定信息失败");
    }

    public OpenIdManage findUserIdByOpenId(String openId) {
        if(StrUtil.isBlank(openId)) throw new CustomException(ResCodeEnum.BAD_REQUEST,"openId不能为空");
        QueryWrapper<OpenIdManage> wrapper = new QueryWrapper<>();
        wrapper.eq("open_id",openId);
        List<OpenIdManage> list = list(wrapper);
        if(list.size() == 0) return null;
        if(list.size() > 1) throw new CustomException(ResCodeEnum.BAD_REQUEST,"错误地存在多个该openId的用户信息");
        return list.get(0);
    }

    public LoginDTO validateTchAndStu(String userId) {
        LoginDTO loginDTO = new LoginDTO();
        loginDTO.setAccountNumber(userId);

        QueryWrapper<Teacher> tchWrapper = new QueryWrapper<>();
        tchWrapper.eq("work_id", userId);
        tchWrapper.select("work_id", "password");
        List<Teacher> tchList = teacherService.list(tchWrapper);
        if (tchList.size() > 1) throw new CustomException(ResCodeEnum.BAD_REQUEST, "错误地存在多个该userId的用户信息");
        if (tchList.size() == 0) {
            QueryWrapper<Student> stuWrapper = new QueryWrapper<>();
            stuWrapper.eq("student_id", userId);
            stuWrapper.select("student_id", "password");
            List<Student> stuList = studentService.list(stuWrapper);
            if (stuList.size() == 0) throw new CustomException(ResCodeEnum.BAD_REQUEST, "该userId的用户信息不存在");
            if (stuList.size() > 1) throw new CustomException(ResCodeEnum.BAD_REQUEST, "错误地存在多个该userId的用户信息");
            loginDTO.setRole(0);  //学生
            loginDTO.setPassword(stuList.get(0).getPassword());
        }
        if (tchList.size() == 1) {
            loginDTO.setRole(1);  //教师
            loginDTO.setPassword(tchList.get(0).getPassword());
        }

        return loginDTO;
    }
}
